package com.wx.chat.controller;


import com.wx.chat.model.ChatMessage;
import com.wx.chat.model.UserEntity;
import com.wx.chat.service.LoginService;
import com.wx.common.api.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @Auther 田艺鹏
 * @DateTime 2020-08-07 18:07
 */
@RestController
@RequestMapping(value = "/chat")
@Api(tags = "后台实时聊天")

public class LoginController {
    @Autowired
    private LoginService loginService;


    @ApiOperation(value = "聊天登录", notes = "聊天登录")
    @PostMapping("/login")
    public CommonResult Login( @RequestBody UserEntity userEntity){
        UserEntity login = loginService.login(userEntity);
        if(login != null){
            System.out.println("欢迎您:"+login.getNickname ());
        }else{
            System.out.println("登录失败！");
            return CommonResult.failed("登录失败");
        }
        return CommonResult.success (login,"登录成功！");
    }

    @ApiOperation(value = "聊天注册", notes = "聊天注册")
    @PostMapping("/register")
    public CommonResult register(@RequestBody UserEntity userEntity){
        if(loginService.checkUser(userEntity.getUserId()) == null){
            int register = loginService.register(userEntity);
            if(register == 1){
                System.out.println("注册成功！");
                return CommonResult.success("注册成功！");
            }else{
                System.out.println("注册失败");
                return CommonResult.failed("注册失败");
            }
        }else{
            System.out.println("用户已存在，请重新注册！");
            return CommonResult.failed("用户已存在，请重新注册！");
        }
    }


    @MessageMapping("/chat.sendMessage")
    @SendTo("/topic/public")
    public ChatMessage sendMessage( @Payload ChatMessage chatMessage) {
        return chatMessage;
    }

    @MessageMapping("/chat.addUser")
    @SendTo("/topic/public")
    public ChatMessage addUser( @Payload ChatMessage chatMessage,
                               SimpMessageHeaderAccessor headerAccessor) {
        // 添加用户名到会话session
        headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
        return chatMessage;
    }



}
